<template>
    <div id="en">
        <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
        <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
        <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
        <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
        <table>
            <tr>
                <th>名字</th>
                <th>数量</th>
            </tr>
            <tr v-for="(item, index) in list" :key="item.id">
                <td>{{ item.name }}</td>
                <td>{{ item.num }}个</td>
            </tr>
        </table>

        <p>礼物总数：{{ totalCountFn() }} 个</p>
    </div>

</template>

<script>
    export default {
        name: "7-v-computed计算属性",
        data() {
            return {
                // 现有的数据
                list: [
                    { id: 1, name: '篮球', num: 3 },
                    { id: 2, name: '玩具', num: 2 },
                    { id: 3, name: '铅笔', num: 5 },
                ]
            }
        },
        methods: {
            totalCountFn () {
                console.log('methods方法执行了')
                let total = this.list.reduce((sum, item) => sum + item.num, 0)
                return total
            }
        },
        computed: {
            totalCount () {
                // 基于现有的数据，编写求值逻辑
                // 计算属性函数内部，可以直接通过 this 访问到 app 实例
                // console.log(this.list)

                // 需求：对 this.list 数组里面的 num 进行求和 → reduce
                let total = this.list.reduce((sum, item) => sum + item.num, 0)
                return total
            }
        }
    }
</script>

<style scoped>

</style>
